/**
 Ceated by Amit Mudgal (MicroStrategy Principal Designer) for GMS on 6/20/2014
 *
 */

$(document).ready(function() {
	//$("[readonly='readonly']").css({"background":"red"});
	
	var userId = '8165840';
	
	$("#prestatusDate").val(uam.Utils.date2String(new Date()));
	
	if ($.cookie("TransferData") != null && $.cookie("TransferData") != "" && $.cookie("TransferData") != " ") {
		var alldata = $.cookie("TransferData").split("|");
	    var employeeNumber = alldata[0].replace("\"","");
	    var givenName = alldata[1];
	    var sn = alldata[2];
	    var axppmiddlename = alldata[3];
	    var axppdepartment = alldata[4];
	    var axppbusiness_cd = alldata[5];
	    var axppbusiness_descr = alldata[6];
	    var axppcccd = alldata[7];
	    var mail = alldata[8];
	    var axppmanagerid = alldata[9];
	    var axppunit_cd= alldata[10];
	    var axppunit_descr= alldata[11];
	    var axpwebid = alldata[12].replace("\"","");
	    if(axppmiddlename.replace("axppmiddlename:","")=="null"){
	    	var middleName = "";
	    }
	    if(axppbusiness_cd.replace("axppbusiness_cd:","")=="null"){
	    	var busnUDesc = "";
	    }
	    $('#preMstrAType').val("PA"); 
	    $('#preemail').val(mail.replace("mail: ",""));
	    $('#preempContID').val(employeeNumber.replace("employeenumber: ",""));
	    $('#preCostCenter').val(axppcccd.replace("axppcc-cd: ",""));
	    $('#preamexWebID').val(axpwebid.replace("uid: ",""));
	    $('#disabledPreFN').val(givenName.replace("givenName: ",""));
	    $('#disabledPreLN').val(sn.replace("sn: ",""));
	    $('#disabledPreMN').val(middleName);
	    $('#preAmexUC').val(axppunit_cd.replace("axppunit_cd: ",""));
	    $('#preAmexUDesc').val(axppunit_descr.replace("axppunit_descr: ",""));
	    $('#predepartmentId').val(axppdepartment.replace("axppdepartment: ",""));
	    $('#preDeprmntDesc').val(axppdepartment.replace("axppdepartment: ",""));
	    $('#eupDeptDescDynamic').val(axppdepartment.replace("axppdepartment: ",""));
	    //$('#preBusnUC').val(axppbusiness_cd.replace("axppbusiness_cd:",""));
	    $('#preBusnUC').val(busnUDesc);
	    $('#preBusnUD').val(axppbusiness_descr.replace("axppbusiness_descr: ",""));
	    
	    userId = employeeNumber.replace("employeenumber: ","");
	    
	} else {
//		 throw new Error("TransferData cookie is empty or unavailable");
	}
	
	// Initialization Available Products
	uam.par.initProjects();
	
	// Initialization Functionnal Group/Role
	uam.par.initFuncGroup();
	uam.par.initFuncRole();
	
	// Secondary Functional Group/Role
	uam.par.initSecondaryFunctionalGroupRole(userId);
	
	/*
	  test 
	 */
	/*$("#preCostCenter").val("11111111111");
	$("#predepartmentId").val("1111111");
	$("#preemail").val("a@a.c");
	$("#preMEmail").val("a@a.c");
	$("#prefirstname").val("aaa");
	$("#prephone").val("1111111111");
	$("#prelastname").val("bbbb");
	$("#preVPName").val("dfasdf");
	//a.options[0].selected = true;
	//$("#funcGroupStep1 option:first").prop("selected", 'selected');
	$('#funcGroupStep1').get(0).selectedIndex = 2;
	$("#preamexWebID").val("rlav");
	$('#eupDeptDescDynamic').val("R22222");*/
	
});


window.uam = window.uam || {}; // Project: UAM
uam.par = uam.par || {}; // Page: PreApproved_Registration
// MicroStrategy Product Select
uam.par.initProjects = function() {
	uam.Utils.callTask({taskId:"N001", TaskSubID: "GetAllProj" }, function(data) {
		//console.log(data);
		eval("responseContent = " + data);
		if (responseContent.status == uam.Utils.responseCode.OK) {
			var projData = responseContent.data;
			
			$("#srcList").empty();
			console.log(projData.length);
			for (var i = 0; i < projData.length; i++) {
				// [{  "MS_PROJ_ID": 1, "MS_PROJ_NM": "MARC", "CREAT_TS": "2009-06-03 05:58:24.203" }]
				$("<option ondblclick='addSrcToDestList()'/>")
				.val(projData[i]["MS_PROJ_ID"])
				.append(uam.Utils.trim(projData[i]["MS_PROJ_NM"], ""))
				.appendTo("#srcList");
			}
		}
		
	});
}
uam.par.initFuncGroup = function() {
	taskUrl = './taskProc';
	data = {}
	$.ajax({
		url:  taskUrl,
		type: 'GET',
		data: {
		      taskId:'N001',
		      taskEnv:'xml',
		      taskContentType:'xml',
		      TaskSubID:'FunctionalGroup',
		      param1:'User'
		    },
		cache: "false",
		dataType: "xml",
		async: true, //set to false in case we want it to wait
		success: function(data) {
			$(data).find('taskResponse').each(function(){
	    		 $(this).find('indexgrp').each(function(){
                  //alert($(this).text() );
                  var all = $(this).text().split(",");
                  var value = all[1];
                  var Group = all[0];
                  $("#funcGroupStep1").append('<option value=' +value + '>' + Group + '</option>');
	    	      })
	    	 }) 
	    	
		} ,
		error: function (XMLHttpRequest, textStatus, errorThrown) {
	    }

	});
}
uam.par.initFuncRole = function() {
	
	taskUrl1 = './taskProc';
	data = {}
	
	$.ajax({
		url:  taskUrl1,
		type: 'GET',
		data: {
		      taskId:'N001',
		      taskEnv:'xml',
		      taskContentType:'xml',
		      TaskSubID:'FunctionalRole',
		      param1:'Role'
		    },
		cache: "false",
		dataType: "xml",
		async: false, //set to false in case we want it to wait
		success: function(data) {
				$(data).find('taskResponse').each(function(){
                  
	    		 $(this).find('indexrole').each(function(){
	    	    // console.log("into funtcRoleStep2");
                 var fullData = $(this).text().split(",");
                 var val = fullData[1];
                 var Role = fullData[0];
                 var grpVal = fullData[2];
                 /*console.log("val::"+val);
                 console.log("Role::"+Role);
                 console.log("grpVal::"+grpVal);*/
                 $("#funtcRoleStep2").append('<option value=' + val + ' class='+ grpVal  + '>' + Role + '</option>');
	    	     })
	    	 })
		
		} ,
		error: function (XMLHttpRequest, textStatus, errorThrown) { alert('Error');
	    }

	});
}

uam.par.initSecondaryFunctionalGroupRole = function(userId) {
	uam.Utils.callTask({taskId:"N001", TaskSubID: "GetSecFuncGrpRoleData", userid : userId }, function(data) {
		
		//console.log("Callback: GetSecFuncGrpRoleData");
		//console.log(data);
		eval("var responseContent = " + data);
		if (responseContent.status == uam.Utils.responseCode.OK) {
			
			var securityData = responseContent.data;
			// Object {roleID: 2, reasonList: Array[4], funcGroupList: Array[9], funcGroupRoleList: Array[22]}
			//console.log(securityData);
			
			var roleID = securityData.roleID;
			var reasonList = uam.Utils.getObjectList(securityData.reasonList);
			var funcGroupList = uam.Utils.getObjectList(securityData.funcGroupList);
			var funcGroupRoleList = uam.Utils.getObjectList(securityData.funcGroupRoleList);
			
			/*
			console.log("initial 'Secondary Functional Group/Role' ... ");
			console.log("Role ID: " + roleID);
			console.log("reasonList: " + reasonList);
			console.log("funcGroupList: " + funcGroupList);
			console.log("funcGroupRoleList: " + funcGroupRoleList);
			*/
			var grpName = null;
			var grpID = null;
			var roleList = [];
			
			// get groupID and groupName
			for ( var i = 0; i < funcGroupRoleList.length; i++ ) {
				// {FUNC_GRP_ID: "1", FUNC_GRP_ROLE_ID: "7", FUNC_GRP_ROLE_NM: "Regional & Local Support"}
				if (funcGroupRoleList[i]["FUNC_GRP_ROLE_ID"] == roleID) {
					grpID = funcGroupRoleList[i]["FUNC_GRP_ID"];
					break;
				}
			}
			
			for ( var i = 0; i < funcGroupList.length; i++ ) {
				// {radioName: "OptBlue", radio: "8"} 
				if (funcGroupList[i].radio == grpID) {
					grpName = funcGroupList[i].radioName;
					grpID = funcGroupList[i].radio;
				}
			}
			
			//console.log("goupID: " + grpID + ", groupName: " + grpName);
			
			if (grpName != null) {
				
				for ( var i = 0; i < funcGroupRoleList.length; i++ ) {
					// {FUNC_GRP_ID: "1", FUNC_GRP_ROLE_ID: "7", FUNC_GRP_ROLE_NM: "Regional & Local Support"}
					if (funcGroupRoleList[i]["FUNC_GRP_ID"] == grpID) {
						roleList.push(funcGroupRoleList[i]);
					}
				}
				
				uam.par.initSecFuncGrpAndRoleContainer(grpName, roleList, roleID);
				uam.par.initSubSecFuncContainer(grpName, reasonList);
			}
		}
		
	});
}

uam.par.initSecFuncGrpAndRoleContainer = function(grpName, roleList, userRoleID) {
	
	/*	
	<select id="secGrpRoleSelector" onchange="$('#subSecFuncContainer').show()">
		<option>--</option>
		<option value="detailAllAccess">Derail with all access</option>
		<option value="detailMarketing">Detail with Marketing Eligibility restriction</option>
	</select>
	 */	
	
	var container = $("#secFuncGrpAndRoleContainer").empty();
	
	// append the title
	container.append("<div style='font-weight:bold;'>" + grpName +"</div>");
	
	// append the dropdown box
	var selector = $("<select id='secGrpRoleSelector' name='secGrpRoleSelector'></select>").change(uam.par.showSubSecFuncContainer).appendTo(container);
	
	// append the options
	selector.append("<option value='-1'>--</option>");
	for ( var i = 0; i < roleList.length; i++ ) {
		// role format: {FUNC_GRP_ID: "1", FUNC_GRP_ROLE_ID: "7", FUNC_GRP_ROLE_NM: "Regional & Local Support"}
		
		//<option value="detailAllAccess">Derail with all access</option>
		var role = roleList[i];
		
		var option = $("<option></option>").val(role["FUNC_GRP_ROLE_ID"]).append(role["FUNC_GRP_ROLE_NM"]).appendTo(selector);
		
		if (userRoleID == role["FUNC_GRP_ROLE_ID"]) {
			option.css("color","blue");
		} 
		
		// console.log(option.prop("outerHTML"));
	}
}

uam.par.showSubSecFuncContainer = function(event) {
	if (this.value == "-1") {
		$('#subSecFuncContainer').hide();
	} else {
		$('#subSecFuncContainer').show();
	}
}

uam.par.initSubSecFuncContainer = function(grpName, reasonList) {
	
	$("#subSecFuncContainer_reasonTitle").text("Select the reason for " + grpName + " access:");
	var reasonOther = null;
	var reasonIDs = "";
	var reasonPrefix = "reason_";
	for (var i = 0; i < reasonList.length; i++) {
		var reason = reasonList[i];
		var reasonID = reason["OPT_BLUE_ACS_RSN_CD"];
		var reasonDesc = reason["OPT_BLUE_ACS_RSN_DS"];
		
		if (typeof(reasonDesc) == 'object') {// Other reason name = '{}'
			$("#subSecFuncContainer_reasonOther")
			.append("<input type='hidden' value='" + reasonID + "' name='reasonOtherID'></input>")
			.append("<input type='checkbox' id='reasonOther' name='reasonOther' />")
			.append("<label for=reasonOther style='font-weight: normal;'>Other</label>")
			.append("<input type='text' id='reasonOtherContent'  name='reasonOtherContent' />")
			.append("<div class='status' style='display:inline-block;'></div>");
		} else {
			var id = reasonPrefix + reasonID;
			$("#subSecFuncContainer_reasons")
			.append("<input type='checkbox' id='" + id + "' name='" + id + "' />")
			.append("<label for=" + id + " style='font-weight: normal;'>" + reasonDesc + "</label>");
			
			reasonIDs += id + ",";
		}
		
	}
	
	// save all reason IDs except the other_reason
	$("<input id='reasonPrefix' name='reasonPrefix' type='hidden' />").val(reasonPrefix).appendTo("#subSecFuncContainer");
	$("<input id='reasonIDs'name='reasonIDs' type='hidden' />").val(reasonIDs).appendTo("#subSecFuncContainer");
	
}
// reasons validate
uam.par.validateSecFuncGroupRoleReason = function(value, element){
    	
	// reasonPrefix reasonIDs reasonOtherContent
	if ($("#reasonOther").is(":checked") == true) {
		return true;
	} else {
		// var reasonPrefix = $("#reasonPrefix").val();
		var reasonIDs = $("#reasonIDs").val();
		var reasonArray = reasonIDs.split(",");
		for (var i = 0; i < reasonArray.length; i++) {
			if ($("#" + reasonArray[i]).is(":checked") == true){
				return true;
			}
		}
		/*for (var n in uam.eup.reasonList) {
			if(uam.eup.reasonList[n] == true) {
				return true;
			}
		}*/
	}
	return false;
}
